package com.yc.music.tool;

import ohos.eventhandler.EventHandler;

import com.yc.music.inter.EventCallback;
import com.yc.music.service.PlayService;

/**
 * 定时器
 *
 * @since 2021-05-10
 */
public class QuitTimerHelper {
    private static final long SECOND_IN_MILLIS = 1000L;
    private PlayService mPlayService;
    private EventCallback<Long> mTimerCallback;
    private EventHandler mHandler;
    private long mTimerRemain;
    private Runnable mQuitRunnable = new Runnable() {
        @Override
        public void run() {
            mTimerRemain -= SECOND_IN_MILLIS;
            if (mTimerRemain > 0) {
                mTimerCallback.onEvent(mTimerRemain);
                mHandler.postTask(this, SECOND_IN_MILLIS);
            } else {
                mPlayService.quit();
            }
        }
    };

    private QuitTimerHelper() {
    }

    public static QuitTimerHelper getInstance() {
        return SingletonHolder.QUIT_TIMER_INSTANCE;
    }

    /**
     * SingletonHolder
     *
     * @since 2021-05-10
     */
    private static class SingletonHolder {
        private static final QuitTimerHelper QUIT_TIMER_INSTANCE = new QuitTimerHelper();
    }

    /**
     * 初始化      用@NonNull注解，表示不能为null
     *
     * @param playService playService
     * @param handler handler
     * @param timerCallback timerCallback
     */
    public void init(PlayService playService, EventHandler handler,
                     EventCallback<Long> timerCallback) {
        mPlayService = playService;
        mHandler = handler;
        mTimerCallback = timerCallback;
    }

    /**
     * start
     *
     * @param milli 时间
     */
    public void start(long milli) {
        if (mHandler == null) {
            // ToastUtils.showShort("请先进行初始化");
            return;
        }
        stop();
        if (milli > 0) {
            mTimerRemain = milli + SECOND_IN_MILLIS;
            mHandler.postTask(mQuitRunnable);
        } else {
            mTimerRemain = 0;
            mTimerCallback.onEvent(mTimerRemain);
        }
    }

    /**
     * stop
     */
    public void stop() {
        mHandler.removeTask(mQuitRunnable);
    }
}
